﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace MVCCornucopia.Common
{

    public class EmailAddressAttribute : RequiredAttribute, IClientValidatable
    {
        private static readonly Regex emailRegex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + 
               @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + 
               @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");


        public EmailAddressAttribute()
        {
            ErrorMessage = "Enter a valid email address";
        }

        public override bool IsValid(object value)
        {
            return !string.IsNullOrEmpty((string)value) &&
                emailRegex.IsMatch((string)value);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
            ModelMetadata metadata, ControllerContext context)
        {

            return new List<ModelClientValidationRule> {
            new ModelClientValidationRule {
                ValidationType = "email",
                ErrorMessage = this.ErrorMessage
            },
            new ModelClientValidationRule {
                ValidationType = "required",
                ErrorMessage = this.ErrorMessage
            }
        };
        }
    }

}